<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            height: 3000px;
        }

        .nav {
            position: fixed;
            top: 0px;
            width: 100%;
            height: 60px;
            background-color: greenyellow;
            text-align: center;
            line-height: 60px;
            transition: all 1s;
            opacity: 1;
        }

        .box {
            width: 300px;
            height: 300px;
            margin-top: 300px;
            margin-left: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="nav">
        搜索框
    </div>
    <div class="box"></div>


    <script>

        const nav = document.querySelector('.nav')
        const box = document.querySelector('.box')
        window.addEventListener('scroll', function () {
            const n = document.documentElement.scrollTop
            // if (n >= 300) {
            //     nav.style.opacity = 0
            // }
            // else {
            //     nav.style.opacity = 1
            // }
            // 潮流写法
            nav.style.top = n >= box.offsetTop ? '-60px' : '0px'
        })
    </script>
</body>

</html>